package com.schoolhelper.notification.controller;

import com.schoolhelper.notification.domain.Notification;
import com.schoolhelper.notification.service.NotificationService;
import com.schoolhelper.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 通知控制器
 * 提供通知相关的REST API接口
 */
@RestController
@RequestMapping("/api/notifications")
@CrossOrigin(origins = "*")
public class NotificationController {
    
    private static final Logger logger = LoggerFactory.getLogger(NotificationController.class);
    
    @Autowired
    private NotificationService notificationService;
    
    @Autowired
    private JwtUtils jwtUtils;
    
    /**
     * 获取当前用户ID
     */
    private Long getCurrentUserId(HttpServletRequest request) {
        try {
            String token = request.getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7);
                return jwtUtils.getUserIdFromToken(token);
            }
            return null;
        } catch (Exception e) {
            logger.error("获取当前用户ID失败", e);
            return null;
        }
    }
    
    /**
     * 获取用户通知列表
     */
    @GetMapping("/list")
    public Map<String, Object> getNotifications(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "20") int size,
            HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            System.out.println("=== 获取通知列表请求 ===");
            Long userId = getCurrentUserId(request);
            System.out.println("当前用户ID: " + userId);
            
            if (userId == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return response;
            }
            
            System.out.println("查询参数 - page: " + page + ", size: " + size);
            List<Notification> notifications = notificationService.getUserNotifications(userId, page, size);
            response.put("success", true);
            response.put("data", notifications);
            response.put("message", "获取通知列表成功");
            
        } catch (Exception e) {
            System.err.println("获取通知列表异常: " + e.getMessage());
            e.printStackTrace();
            logger.error("获取通知列表失败", e);
            response.put("success", false);
            response.put("message", "获取通知列表失败: " + e.getMessage());
        }
        
        return response;
    }
    
    /**
     * 获取未读通知数量
     */
    @GetMapping("/unread-count")
    public Map<String, Object> getUnreadCount(HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            Long userId = getCurrentUserId(request);
            if (userId == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return response;
            }
            
            int count = notificationService.getUnreadCount(userId);
            
            response.put("success", true);
            response.put("count", count);
            response.put("message", "获取未读通知数量成功");
            
        } catch (Exception e) {
            logger.error("获取未读通知数量失败", e);
            response.put("success", false);
            response.put("message", "获取未读通知数量失败: " + e.getMessage());
        }
        
        return response;
    }
    
    /**
     * 获取未读通知列表
     */
    @GetMapping("/unread")
    public Map<String, Object> getUnreadNotifications(HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            Long userId = getCurrentUserId(request);
            if (userId == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return response;
            }
            
            List<Notification> notifications = notificationService.getUnreadNotifications(userId);
            
            response.put("success", true);
            response.put("data", notifications);
            response.put("message", "获取未读通知列表成功");
            
        } catch (Exception e) {
            logger.error("获取未读通知列表失败", e);
            response.put("success", false);
            response.put("message", "获取未读通知列表失败: " + e.getMessage());
        }
        
        return response;
    }
    
    /**
     * 标记通知为已读
     */
    @PutMapping("/{id}/read")
    public Map<String, Object> markAsRead(@PathVariable Long id, HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            Long userId = getCurrentUserId(request);
            if (userId == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return response;
            }
            
            // 修复：传递用户ID进行权限验证
            boolean success = notificationService.markAsRead(id, userId);
            
            if (success) {
                response.put("success", true);
                response.put("message", "标记已读成功");
            } else {
                response.put("success", false);
                response.put("message", "标记已读失败，通知不存在或无权限");
            }
            
        } catch (Exception e) {
            logger.error("标记通知已读失败", e);
            response.put("success", false);
            response.put("message", "标记已读失败: " + e.getMessage());
        }
        
        return response;
    }
    
    /**
     * 标记所有通知为已读
     */
    @PutMapping("/read-all")
    public Map<String, Object> markAllAsRead(HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            Long userId = getCurrentUserId(request);
            if (userId == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return response;
            }
            
            boolean success = notificationService.markAllAsRead(userId);
            
            if (success) {
                response.put("success", true);
                response.put("message", "全部标记已读成功");
            } else {
                response.put("success", false);
                response.put("message", "全部标记已读失败");
            }
            
        } catch (Exception e) {
            logger.error("标记所有通知已读失败", e);
            response.put("success", false);
            response.put("message", "全部标记已读失败: " + e.getMessage());
        }
        
        return response;
    }
    
    /**
     * 测试接口：获取指定用户的所有通知（用于调试）
     */
    @GetMapping("/test/{userId}")
    public Map<String, Object> getNotificationsForUser(@PathVariable Long userId) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            System.out.println("=== 测试获取用户通知 ===");
            System.out.println("目标用户ID: " + userId);
            
            List<Notification> notifications = notificationService.getUserNotifications(userId, 1, 50);
            System.out.println("查询到的通知数量: " + (notifications != null ? notifications.size() : 0));
            
            if (notifications != null) {
                for (Notification notification : notifications) {
                    System.out.println("通知详情 - ID: " + notification.getId() + 
                                     ", type: " + notification.getType() + 
                                     ", title: " + notification.getTitle() + 
                                     ", isRead: " + notification.getIsRead() +
                                     ", createTime: " + notification.getCreateTime());
                }
            }
            
            int unreadCount = notificationService.getUnreadCount(userId);
            System.out.println("未读通知数量: " + unreadCount);
            
            response.put("success", true);
            response.put("data", notifications);
            response.put("unreadCount", unreadCount);
            response.put("message", "测试获取通知成功");
            
        } catch (Exception e) {
            System.err.println("测试获取通知失败: " + e.getMessage());
            e.printStackTrace();
            response.put("success", false);
            response.put("message", "测试获取通知失败: " + e.getMessage());
        }
        
        return response;
    }
    @DeleteMapping("/{id}")
    public Map<String, Object> deleteNotification(@PathVariable Long id, HttpServletRequest request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            Long userId = getCurrentUserId(request);
            if (userId == null) {
                response.put("success", false);
                response.put("message", "用户未登录");
                return response;
            }
            
            boolean success = notificationService.deleteNotification(id);
            
            if (success) {
                response.put("success", true);
                response.put("message", "删除通知成功");
            } else {
                response.put("success", false);
                response.put("message", "删除通知失败");
            }
            
        } catch (Exception e) {
            logger.error("删除通知失败", e);
            response.put("success", false);
            response.put("message", "删除通知失败: " + e.getMessage());
        }
        
        return response;
    }
}